package com.xiaotu.web.filter;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import com.xiaotu.code.util.MyResponseWrapper;

/**
 * Servlet Filter implementation class WrapperFilter
 */
public class WrapperFilter implements Filter {

    /**
     * Default constructor. 
     */
    public WrapperFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 使用我们自定义的响应包装器来包装原始的ServletResponse  

		MyResponseWrapper wrapper = new MyResponseWrapper(
				(HttpServletResponse) response);  

		   // 这句话非常重要，注意看到第二个参数是我们的包装器而不是原始的servletresponse  

		   //这样容器才会把响应内容写入自定义的包装器中  

		    chain.doFilter(request, wrapper);  

		   // 截获的结果并进行处理  

		   String result = wrapper.getResult(); 
		   System.out.println("拦截页面结果如下所示:");
		   System.out.println(result);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
